﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Linq;

namespace ifunction.BaiduBCS.SDK
{
    /// <summary>
    /// Class StorageObjectMergeRequest.
    /// </summary>
    [DataContract]
    public class StorageObjectMergeRequest : StorageObjectIdentity
    {
        /// <summary>
        /// Gets or sets the object parts.
        /// </summary>
        /// <value>The object parts.</value>
        [DataMember]
        public List<StorageObjectIdentity> ObjectParts
        {
            get;
            set;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="StorageObjectMergeRequest"/> class.
        /// </summary>
        public StorageObjectMergeRequest()
            : base()
        {

        }

        /// <summary>
        /// To the json.
        /// </summary>
        /// <returns>JObject.</returns>
        public JObject ToJson()
        {
            JObject obj = new JObject();

            obj.Add("object_list", ToJson(this.ObjectParts));

            return obj;
        }

        /// <summary>
        /// To the json.
        /// </summary>
        /// <param name="objectIdentity">The object identity.</param>
        /// <returns>JObject.</returns>
        protected JObject ToJson(StorageObjectIdentity objectIdentity)
        {
            if (objectIdentity != null)
            {
                //{"url":"bs://superfile/2.txt","etag":"6936d4a746461b97a2d6c16064794db2"}
                var obj = new JObject();
                obj.Add("url", string.Format("bs://{0}/{1}", objectIdentity.BucketName, objectIdentity.ObjectName).ToLowerInvariant());
                obj.Add("etag", objectIdentity.MD5);

                return obj;
            }

            return null;
        }

        /// <summary>
        /// To the json.
        /// </summary>
        /// <param name="objectIdentityCollection">The object identity collection.</param>
        /// <returns>JObject.</returns>
        protected JObject ToJson(List<StorageObjectIdentity> objectIdentityCollection)
        {
            if (objectIdentityCollection != null)
            {
                JObject result = new JObject();

                int index = 0;
                foreach (var one in objectIdentityCollection)
                {
                    result.Add("part_" + index.ToString(), ToJson(one));
                    index++;
                }

                return result;
            }

            return null;
        }
    }
}
